package com.woniuxy.project115.kaer.mall.controller;


import cn.hutool.core.bean.BeanUtil;
import com.woniuxy.project115.kaer.commons.util.JwtUtil;
import com.woniuxy.project115.kaer.commons.util.Result;
import com.woniuxy.project115.kaer.mall.entity.ProductInfo;
import com.woniuxy.project115.kaer.mall.entity.ProductOrderInfo;
import com.woniuxy.project115.kaer.mall.form.OrderForm;
import com.woniuxy.project115.kaer.mall.param.OrderParam;
import com.woniuxy.project115.kaer.mall.service.ProductOrderInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * <p>
 * 订单详情表 前端控制器
 * </p>
 *
 * @author lyc
 * @since 2025年02月17日
 */
@RestController
@RequestMapping("/orderInfo")
@Api(tags = "商品订单接口")
public class ProductOrderInfoController {
    @Resource
    private ProductOrderInfoService productOrderInfoService;
    private static final Logger logger = LoggerFactory.getLogger(ProductOrderInfoController.class);
    /**
     *
     * @param orderNum 订单号
     * @param token 用户token(获取userId)
     * @return
     * @throws Exception
     */
    @ApiOperation("用户支付订单")
    @PostMapping("pay")
    public Result pay(String orderNum, @RequestHeader String token) throws Exception {
        Integer userId = JwtUtil.getUserId(token);
        String payResult = productOrderInfoService.pay(orderNum, userId);
        return Result.succeed("支付成功", payResult);
    }
    //用户下单

    /**
     *
     * @param form 下单表单
     * @param token
     * @return
     * @throws Exception
     */
    @ApiOperation("用户下单")
    @PostMapping("order")
    public Result order(@RequestBody OrderForm form, @RequestHeader String token) throws Exception {
        OrderParam param = BeanUtil.toBean(form, OrderParam.class);
        param.setUserId(JwtUtil.getUserId(token));
        ProductOrderInfo orderInfo =productOrderInfoService.order(param);
        return Result.succeed("下单成功",orderInfo);
    }
    @ApiOperation("支付宝回调函数请求接口")
    @PostMapping("/notify")
    public String payNotify(HttpServletRequest request) {
            // 获取支付宝 POST 过来的反馈信息
            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
                String name = iter.next();
                String[] values = requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i]
                            : valueStr + values[i] + ",";
                }
                params.put(name, valueStr);
            }
            logger.info("支付宝回调参数: {}", params);
        try {
            // 处理订单
            productOrderInfoService.handleOrder(params);
            return "SUCCESS";
        } catch (Exception e) {
            // 记录异常日志
            logger.error("支付宝回调处理异常: {}", e.getMessage(), e);

            // 获取订单号，根据实际情况修改
            String orderNum = params.get("out_trade_no");
            if (orderNum != null) {
                try {
                    // 状态回滚
                    productOrderInfoService.rollbackOrderStatus(orderNum);
                    logger.info("订单 {} 状态已回滚", orderNum);
                } catch (Exception rollbackException) {
                    logger.error("订单 {} 状态回滚失败: {}", orderNum, rollbackException.getMessage(), rollbackException);
                }

                // 重试机制（简单示例，可根据实际情况修改）
                try {
                    for (int i = 0; i < 3; i++) {
                        try {
                            productOrderInfoService.handleOrder(params);
                            logger.info("订单 {} 重试处理成功", orderNum);
                            return "SUCCESS";
                        } catch (Exception retryException) {
                            logger.error("订单 {} 第 {} 次重试处理失败: {}", orderNum, i + 1, retryException.getMessage(), retryException);
                        }
                    }
                } catch (Exception retryLoopException) {
                    logger.error("订单 {} 重试处理异常: {}", orderNum, retryLoopException.getMessage(), retryLoopException);
                }

                // 人工干预
                logger.error("订单 {} 多次重试失败，请人工处理", orderNum);
            }

            return "FAIL";
        }
    }
    //取消订单

    /**
     *
     * @param orderNum 订单编号
     * @return
     * @throws Exception
     */
    @ApiOperation("取消订单")
    @PutMapping("cancelOrder")
    public Result cancelOrder(String orderNum) throws Exception {
        productOrderInfoService.cancelOrder(orderNum,1);
        return Result.succeed("取消成功", null);
    }
    //修改订单备注
    @ApiOperation("修改订单备注")
    @PutMapping("updateRemarks")
    public Result updateRemarks(String orderNum,String remarks){
        productOrderInfoService.updateRemarks(orderNum,remarks);
        return Result.succeed("修改成功",null);
    }
    //用户查询我的待付款订单
    @ApiOperation("用户查询我的待付款订单")
    @GetMapping("getMyUnpaidOrder")
    public Result getMyUnpaidOrder(@RequestHeader String token) throws Exception {
        return Result.succeed("查询成功",productOrderInfoService.getMyUnpaidOrder(JwtUtil.getUserId(token)));
    }
    //用户查询我的待发货订单
    @ApiOperation("用户查询我的待发货订单")
    @GetMapping("getMyUnshippedOrder")
    public Result getMyUnshippedOrder(@RequestHeader String token) throws Exception {
        return Result.succeed("查询成功",productOrderInfoService.getMyUnshippedOrder(JwtUtil.getUserId(token)));
    }
    //用户查询我的待收货订单
    @ApiOperation("用户查询我的待收货订单")
    @GetMapping("getMyUnreceivedOrder")
    public Result getMyUnreceivedOrder(@RequestHeader String token) throws Exception {
        return Result.succeed("查询成功",productOrderInfoService.getMyUnreceivedOrder(JwtUtil.getUserId(token)));
    }
    //用户查询我的待评价订单
    @ApiOperation("用户查询我的待评价订单")
    @GetMapping("getMyUncommentOrder")
    public Result getMyUncommentOrder(@RequestHeader String token) throws Exception {
        return Result.succeed("查询成功",productOrderInfoService.getMyUncommentOrder(JwtUtil.getUserId(token)));
    }
    //用户查询我的已完成订单
    @ApiOperation("用户查询我的已完成订单")
    @GetMapping("getMyCompletedOrder")
    public Result getMyCompletedOrder(@RequestHeader String token) throws Exception {
        return Result.succeed("查询成功",productOrderInfoService.getMyCompletedOrder(JwtUtil.getUserId(token)));
    }
    //用户催发货
    @ApiOperation("用户催发货")
    @PutMapping("urge")
    public Result urge(String orderNum,@RequestHeader String token) throws Exception {
        productOrderInfoService.urge(orderNum,JwtUtil.getUserId(token));
        return Result.succeed("催发货成功",null);
    }
    //用户确认收货
    @ApiOperation("用户确认收货")
    @PutMapping("confirm")
    public Result confirm(String orderNum,@RequestHeader String token) throws Exception {
        productOrderInfoService.confirm(orderNum,JwtUtil.getUserId(token));
        return Result.succeed("确认收货成功",null);
    }
    //平台账户去发货
    @ApiOperation("去发货")
    @PostMapping("/send")
    public Result send(String orderNum){
        productOrderInfoService.send(orderNum);
        return Result.succeed("发货成功",null);
    }
    //平台查询所有订单
    @ApiOperation("平台查询所有订单")
    @GetMapping("getAllOrder")
    public Result getAllOrder(){
        return Result.succeed("查询成功",productOrderInfoService.getAllOrder());
    }
}

